package com.xinyue.server.framework.handler;

import com.xinyue.server.framework.common.GameFrameworkConfig;
import com.xinyue.server.framework.handlermapping.*;
import com.xinyue.server.framework.message.GameMessageHeader;
import com.xinyue.server.framework.message.GameMessagePackage;
import com.xinyue.server.framework.message.GameMessageType;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleStateEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

public class GameRequestDispatcherHandler extends ChannelInboundHandlerAdapter {
    private Logger logger = LoggerFactory.getLogger(GameRequestDispatcherHandler.class);
    @Autowired
    private GameServerCacheService gameChannelService;
    @Autowired
    private GameFrameworkConfig gameFrameworkConfig;
    @Autowired
    private GameServerCacheService gameServerCacheService;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof GameMessagePackage) {
            try {
                GameMessagePackage request = (GameMessagePackage) msg;
                IGameMessage gameMessage = request.getBody();
                GameMessageHeader header = request.getHeader();
                GameChannelContext gtx = new GameChannelContext(ctx, header);
                IGameMessage requestMessage = gameMessage;
                int messageId = header.getLogicMessageId();
                int messageType = GameMessageType.REQUEST.getType();
                MessageClassKey classKey = new MessageClassKey(messageId, messageType);
                GameHandlerMappingManager gameHandlerMappingManager = GameHandlerMappingManager.getInstance();
                gameHandlerMappingManager.callMethod(gtx, classKey, requestMessage);
            } catch (Throwable e) {
                logger.error("处理客户端请求异常", e);
            }
        } else {
            logger.warn("收到非游戏对象请求数据：{}", msg.getClass().getName());
            ctx.fireChannelRead(msg);
        }
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        //接收channel内部的一些事件
        if (evt instanceof IdleStateEvent) {
            logger.debug("channel idle and to be close,{}", ctx.channel().id().asShortText());
            ctx.channel().close();
        }
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        logger.error("服务器内部异常", cause);
    }
}
